/*
 * MKeyPlus
 * BaseApp基座
 * @version 1.0
 * @time 2017-9-7 16:19:41
 */
; (function ($) {
  if (!$) {
    console.log("引用的时，必须先引用mui.min.js！!!")
  }
  var BaseApp = function () { }
  var Token = localStorage.getItem("mqmsToken")
  console.log("Bearer " + Token)
  var bCg = JSON.parse(localStorage.getItem('baseConfig'))
  // localStorage.getItem('serverUrl') ? '' : localStorage.setItem('serverUrl', 'https://neom-t.cgnpc.com.cn/smartreport-api/ding/nemqms/index') // 测试
  localStorage.getItem('serverUrl') ? '' : localStorage.setItem('serverUrl', 'https://neom.cgnpc.com.cn/smartreport-api/nemqms/') // 生产 https://neom-t.cgnpc.com.cn/smartreport-api/ding/nemqms-prod/
  
  BaseApp.prototype.serverUrl = localStorage.getItem('serverUrl');
  /**
   * 打开模块，首先判断是否有文件，如果有文件则打开，没有则下载
   * 默认webview的id和页面路径一致，
   * @param {url} string 页面相对跟目录的全路径   例如：/index2.html
   * @param {extras} object 页面传参 {name:'mui',version:'0.5.8'}
   */
  BaseApp.prototype.startModel = function (url, extras) {
    //检查文件是否存在
    checkPath(url, extras)
    //extras:
  }

  /**
   * http请求
   * @param {url} 请求地址
   * @param {param} http请求参数
   * @param {type} get|post 默认是get
   * @param {success} 成功回调
   * @param {error}  失败回调
   */
  BaseApp.prototype.httpRequst = function (type, url, param, success, error) {
    if (url.indexOf("http://") < 0 && url.indexOf("https://") < 0) {
      url = this.serverUrl + url
    }
    return new Promise(function (resolve, reject) {
      param = param ? param : {}
      param.timestamp = new Date().getTime()
      param.OSType = mui.os.ios ? "ios" : "android"
      //  if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
      //    plus.nativeUI.closeWaiting()
      //    if(typeof(error) == "function") {
      //      error({
      //        msg: '无网络'
      //      });
      //    }
      //    return;
      //  }
      let headers = {
        Authorization: "Bearer " + localStorage.getItem("mqmsToken"),
      }
      if (type == "post" || type == "put") {
        headers["Content-Type"] = "application/json"
        param = JSON.stringify(param)
      }
      console.log(JSON.stringify(param))
      console.log(url)
      console.log(type)
      // 添加固定参数
      mui.ajax(url, {
        data: param,
        dataType: "json", //服务器返回json数据
        type: type ? type : "get", //http请求类型
        headers: headers,
        timeout: 1000000,
        success: function (data) {
          if (data.code == 'E10401') {
            mui.toast('Token超时，请退出APP重新登录')
            return
          }
          if (data.code == 1) {
            mui.toast(data.msg)
            if (typeof error == "function") {
              error(data)
            }
            reject(data)
            return
          }
          if (typeof success == "function") {
            success(data)
          }
          resolve(data)
        },
        error: function (xhr, type, errorThrown) {
          console.log(JSON.stringify(xhr.responseText) + "")
          console.log(type)
          console.log(errorThrown)
          console.log(typeof error)
          console.log("-------" + localStorage.getItem("mqmsToken"))
          if (
            plus.networkinfo.getCurrentType() !=
            plus.networkinfo.CONNECTION_NONE
          ) {
            mui.toast(xhr.responseText ? JSON.parse(xhr.responseText).message : '网络错误')
          }
          if (typeof error == "function") {
            error(errorThrown)
          }
          reject(errorThrown)
        },
      })
    })
  }

  /**
   * 文件上传请求
   * @param {path} 文件路径
   * @param {success} 成功回调
   * @param {error}  失败回调
   */
  BaseApp.prototype.upLoadFile = async function (path, success, error) {
    if (plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
      mui.toast("无网络")
      if (typeof error === "function") {
        error({
          msg: "无网络",
        })
      }
      return
    }
    var task = await plus.uploader.createUpload(
      this.serverUrl + "/outsider/general/upload",
      {
        method: "POST",
      },
      function (t, status) {
        // 上传完成
        console.log(t.responseText)
        console.log(status)
        if (status == 200) {
          let data = JSON.parse(t.responseText)
          if (data.code == 1) {
            mui.toast(data.msg)
            if (typeof error === "function") {
              error(data)
            }
            return
          }
          if (typeof success === "function") {
            success(data)
          }
          console.log("Upload success: ")
        } else {
          console.log("Upload failed: " + status)
        }
      }
    )
    task.addData("file", "file")
    task.addFile(path, {
      key: "fileData",
    })
    // 设置自定义数据头
    task.setRequestHeader(
      "Authorization",
      "Bearer " + localStorage.getItem("mqmsToken")
    )
    task.start()
  }
  /**
   * 文件上传请求
   * @param {file} 文件
   * @param {success} 成功回调
   * @param {error}  失败回调
   */
  BaseApp.prototype.upLoadFile1 = function (file, success, error) {
    //  if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
    //    mui.toast('无网络')
    //    if(typeof error === 'function') {
    //      error({
    //        msg: '无网络'
    //      })
    //    }
    //    return
    //  }
    var formData = new FormData()
    formData.append("fileData", file)
    mui.ajax({
      type: "POST",
      url: this.serverUrl + "/outsider/general/upload",
      data: formData,
      headers: {
        Authorization: "Bearer " + localStorage.getItem("mqmsToken"),
      },
      processData: false,
      contentType: false,
      success: function (data) {
        console.log(data)
        if (data.code == 1) {
          mui.toast(data.msg)
          if (typeof error === "function") {
            error(data)
          }
          return
        }
        if (typeof success === "function") {
          success(data)
        }
      },
      error: function (err) {
        console.log("error")
        console.log(err)
        if (typeof error === "function") {
          error(error)
        }
      },
    })
  }
  /**
   * base64 转本地文件
   * @param {base64} base64编码
   */
  BaseApp.prototype.base64ToPath = function (base64) {
    return new Promise(function (resolve, reject) {
      if (typeof plus === "object") {
        var basePath = "_doc"
        var dirPath = "mqms/sign"
        let fileName = new Date().getTime() + ".png"
        var filePath = basePath + "/" + dirPath + "/" + fileName
        console.log("filePath=" + filePath)
        var bitmap = new plus.nativeObj.Bitmap(fileName)
        bitmap.loadBase64Data(
          base64,
          function () {
            bitmap.save(
              filePath,
              {},
              function () {
                bitmap.clear()
                resolve(filePath)
              },
              function (error) {
                bitmap.clear()
                reject(error)
              }
            )
          },
          function (error) {
            bitmap.clear()
            reject(error)
          }
        )
        return
      }
      if (typeof window === "object" && "document" in window) {
        base64 = base64.split(",")
        var type = base64[0].match(/:(.*?);/)[1]
        var str = atob(base64[1])
        var n = str.length
        var array = new Uint8Array(n)
        while (n--) {
          array[n] = str.charCodeAt(n)
        }
        return resolve(
          (window.URL || window.webkitURL).createObjectURL(
            new Blob([array], {
              type: type,
            })
          )
        )
      }
    })
  }
  /**
   * 页面跳转
   * @param {url} 页面路径
   * @param {extras} 跳转携带参数
   * @param {subpages} 子页面
   * @param {show} 页面展示方式
   */
  BaseApp.prototype.openWindow = function (url, extras, subpages, show) {
    //打开新页面
    mui.openWindow({
      url: url,
      id: url.indexOf("?") > 0 ? url.substring(0, url.indexOf("?")) : url,
      show: show
        ? show
        : {
          autoShow: true,
          aniShow: "slide-in-right",
          duration: "200", //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；
        },
      waiting: {
        autoShow: false,
      },
      subpages: subpages ? subpages : {},
      extras: extras ? extras : {},
    })
  }

  /**
   * 时间戳转换
   * @param {timestamp} 时间戳
   * @param {format} 时间格式
   */
  BaseApp.prototype.formatDate = function (timestamp, format) {
    if (timestamp == null || String(timestamp).trim() == "") {
      return timestamp
    }
    if (format == null || format.trim() == "") {
      format = "yyyy-MM-dd"
    }
    timestamp += ""
    if (timestamp.length <= 11) {
      timestamp = parseInt(timestamp) * 1000
    } else {
      timestamp = parseInt(timestamp)
    }
    var tempDate = new Date(timestamp)
    let DayList = ["日", "一", "二", "三", "四", "五", "六"]
    var date = {
      "M+": tempDate.getMonth() + 1, //月份
      "d+": tempDate.getDate(), //日
      "h+": tempDate.getHours(), //小时
      "m+": tempDate.getMinutes(), //分
      "s+": tempDate.getSeconds(), //秒
      "q+": Math.floor((tempDate.getMonth() + 3) / 3), //季度
      "S+": tempDate.getMilliseconds(), //毫秒
      "D+": "周" + DayList[tempDate.getDay()],
    }
    if (/(y+)/i.test(format)) {
      format = format.replace(
        RegExp.$1,
        (tempDate.getFullYear() + "").substr(4 - RegExp.$1.length)
      )
    }
    for (var k in date) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? date[k]
            : ("00" + date[k]).substr(("" + date[k]).length)
        )
      }
    }
    return format
  }
  /**
   * 下载
   * @param {url} 下载路径
   * @param {filename} 下载存储路径
   * @param {success} 下载成功
   * @param {error} 下载失败
   */
  BaseApp.prototype.download = function (url, filename, success, error) {
    return new Promise((resolve, reject) => {
      if (plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
        mui.toast("无网络")
        if (typeof error === "function") {
          error({
            msg: "无网络",
          })
          reject({
            msg: "无网络",
          })
        }
        return
      }
      //判断是否是完整URL
      if (url.indexOf("http://") < 0 && url.indexOf("https://") < 0) {
        //相对url
        url = this.serverUrl + url
      }
      console.log("downUrl", url)
      var dtask = plus.downloader.createDownload(
        url,
        {
          filename: "_doc/mqms/" + filename,
          timeout: 15,
          retryInterval: 5
        },
        function (d, status) {
          if (status == 200) {
            console.log(d)
            console.log("下载完成")
            if (typeof success === "function") {
              success(d)
              resolve(d)
            }
          } else {
            mui.toast("文件下载失败")
            if (typeof error === "function") {
              error(d)
            }
            reject(d)

          }
        }
      )
      dtask.setRequestHeader(
        "Authorization",
        "Bearer " + localStorage.getItem("mqmsToken")
      )
      //监听下载状态
      dtask.addEventListener("statechanged", function (task, status) {
        if (!dtask) {
          return
        }
        console.log("==========下载===========")
        switch (task.state) {
          case 1: // 开始
            console.log("开始下载...")
            break
          case 2: // 已连接到服务器
            console.log("链接到服务器...")
            break
          case 3: // 已接收到数据
            console.log(task.downloadedSize)
            break
          case 4: // 下载完成
            console.log(task.totalSize)
            break
        }
      })
      dtask.start()
    })
  }
  /**
   * 选择照片
   */
  BaseApp.prototype.chooseImg = function () {
    let self = this
    return new Promise(function (resolve, reject) {
      var buttonTit = [{
        title: "拍照"
      }, {
        title: "从相册中选择"
      }];

      plus.nativeUI.actionSheet({
        cancel: "取消",
        buttons: buttonTit
      }, function (b) { /*actionSheet 按钮点击事件*/
        switch (b.index) {
          case 0:
            break;
          case 1:
            self.camera().then(res => {
              resolve(res)
            }); /*拍照*/
            break;
          case 2:
            self.galleryImg().then(res => {
              resolve(res)
            });; /*打开相册*/
            break;
          default:
            break;
        }
      })
    })
  }
  /**
   * 相册选择
   */
  BaseApp.prototype.galleryImg = function () {
    let self = this
    return new Promise(function (resolve, reject) {
      plus.gallery.pick(function (path) {
        resolve(path);
      });
    })
  }
  /**
   * 拍照
   */
  BaseApp.prototype.camera = function () {
    let self = this
    return new Promise(function (resolve, reject) {
      var cameraObj = plus.camera.getCamera()
      cameraObj.captureImage(
        function (path) {
          self.compressImage(path).then(res => {
            resolve(res)
          })
        },
        function (e) {
          console.log("取消拍照")
          console.log(e)
          if (e && e.message == 'No Permission') {
            plus.nativeUI.toast("读取拍照文件错误：请先开启相机权限");
          }
          reject("取消")
        },
        {
          filename: "_doc/camera/",
          index: 1,
        }
      )
    })
  }
  /**
   * 图片压缩
   * @param {patn} 图片路径
   */
  BaseApp.prototype.compressImage = function (path) {
    return new Promise(function (resolve, reject) {
      plus.zip.compressImage(
        {
          src: path,
          dst: path,
          overwrite: true,
          width: "50%",
          quality: 60,
        },
        function (event) {
          console.log(event)
          var src = event.target
          resolve(src)
        }
      )
    })
  }

  /**
   * 获取字典
   * @param {dictNameArr} 字典名称数组   需先在index页面获取
   */
  BaseApp.prototype.getDict = async function (dictNameArr) {
    let data = {
      code: {},
      id: {},
      label: {},
      value: {}
    }
    let ps = []
    dictNameArr.forEach(dictName => {
      ps.push(mui.DB.selectTableData('dict', [{ key: 'dictName', value: dictName }]).then(res => {
        data[dictName] = []
        data.code[dictName] = {}
        data.id[dictName] = {}
        data.label[dictName] = {}
        data.value[dictName] = {}
        if (!Array.isArray(res)) {
          return ''
        }
        data[dictName] = res
        res.forEach(item => {
          data.code[dictName][item.code] = item
          data.id[dictName][item.id] = item
          data.label[dictName][item.label] = item
          data.value[dictName][item.value] = item
        })
        return data
      }))

    })
    await Promise.all(ps);
    return data
  }

  // document.write(
  //   "<script language=javascript src='https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/vConsole/3.12.1/vconsole.min.js'></script>"
  // )
  // document.write(
  //   "<script type='text/javascript'>var vConsole = new VConsole();</script>"
  // )
  $.baseApp = new BaseApp()
})(mui)
